import dom, { ajax } from "../../init.js";
import { obj } from "../../index.js";
import event from "./eventhandle.js";
import file from "./file.js";
import { getUserInfo } from "../../../util/interface.js";
import { initcomment } from "../comment/comment.js";
import { toarticle } from "../../navigation/eventhandle.js";

dom.user.userImg.onclick = file.userImg;
dom.user.imgipt.onchange = file.change;

export async function islogin() {
  const data = await ajax.post("/user/islogin");
  const { data: info } = JSON.parse(data as string) as getUserInfo;
  event.chongzhi();
  if (info) {
    obj.islogin = true;
    //如果登录成功并且停留在文章页面就会刷新文章
    if (dom.index.article.classList.length >= 2) toarticle();
    dom.user.mubuevent.breaklogin.style.display = "block";
    dom.index.shuoshuo.style.display = "block";
    dom.user.mubuevent.islogin.style.display = "none";
    dom.user.name.innerText = info.name;
    obj.isAndmi = false;
    if (info.right == 1 || info.right == 2) {
      if (+info.right === 1) {
        dom.user.nickname.innerHTML =
          info.nickName + '<span class="right1">Admi</span>';
        dom.index.andmi.style.display = "block";
        obj.isAndmi = true;
      }
      if (+info.right === 2) {
        dom.user.nickname.innerHTML =
          info.nickName + '<span class="right2">VIP1</span>';
      }
    } else {
      dom.user.nickname.innerHTML = info.nickName;
    }
    dom.user.userImg.innerText = "点击更换头像";
    if (info.imgUrl) {
      dom.user.imgurl.setAttribute("src", info.imgUrl);
    } else {
      dom.user.imgurl.setAttribute("src", "./img/空.jpg");
    }
  } else {
    dom.user.mubuevent.breaklogin.style.display = "none";
    dom.index.shuoshuo.style.display = "none";
    obj.islogin = false;
    dom.user.name.innerText = "游客";
    dom.user.nickname.innerText = "旅行者";
    dom.user.imgurl.setAttribute("src", "./img/空.jpg");
    dom.user.userImg.innerText = "点击登录";
  }
  if (dom.index.comment.classList.length >= 2) {
    initcomment();
  }
}
